package com.hello.rabbithandler;

import com.Constants;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableRabbit
@ComponentScan("com.hello.rabbithandler")
public class HelloRabbitHandlerMqConfiguration {

    @Bean
    public CachingConnectionFactory connectionFactory() {
        return new CachingConnectionFactory("localhost");
    }

    @Bean
    public RabbitAdmin amqpAdmin() {
        return new RabbitAdmin(connectionFactory());
    }

    @Bean
    public Queue myQueue() {
        return new Queue(Constants.QUEUE_NAME);
    }

    /**
     * 此消息转换器在设置RabbitTemplate时设置
     *
     * 默认使用的是SimpleMessageConverter转换器,其支持byte数组，字符串，实现了Serializable接口的对象
     *
     * 目前的版本不能设置多个消息转换器,见https://github.com/spring-projects/spring-amqp/issues/827 有讨论
     * 不能使用org.springframework.messaging.converter.CompositeMessageConverter
     * 类型来达成封装多个转换器的逻辑，因为它实现的org.springframework.messaging.converter.MessageConverter接口，
     * 而不是RabbitTemplate与SimpleRabbitListenerContainerFactory所需要的org.springframework.amqp.support.converter.MessageConverter，
     * 这两个接口名字一样，但不是同一个，不能通用
     * @return
     */
    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        //设置发送消息的消息转换器
        template.setMessageConverter(messageConverter());
        return template;
    }


    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        //设置接收消息的消息转换器
        factory.setMessageConverter(messageConverter());
        return factory;
    }
}
